<template>
  <view class="container">
    <!-- 登录方式切换 -->
    <view class="tab-container">
      <view
          class="tab-item"
          :class="{ active: activeTab === 1 }"
          @click="activeTab = 1"
      >
        账号登录
      </view>
      <view
          class="tab-item"
          :class="{ active: activeTab === 2 }"
          @click="activeTab = 2"
      >
        手机登录
      </view>
      <view
          class="tab-item"
          :class="{ active: activeTab === 3 }"
          @click="activeTab = 3"
      >
        QQ邮箱登录
      </view>
    </view>

    <!-- 账号密码登录 -->
    <view v-show="activeTab === 1" class="form-container">
      <input
          class="input-item"
          v-model="account"
          placeholder="请输入账号"
      />
      <view class="password-input">
        <input
            class="input-item"
            v-model="password"
            :password="!showPassword"
            placeholder="请输入密码"
        />
        <text
            class="icon-eye"
            @click="showPassword = !showPassword"
        >{{ showPassword ? '👁' : '👁️🗨' }}
        </text>
      </view>

      <view class="remember-forgot">
        <label>
          <checkbox :checked="remember" @click="remember = !remember"/>
          记住密码
        </label>
        <text class="forgot-password">忘记密码？</text>
      </view>
    </view>

    <!-- 手机号登录 -->
    <view v-show="activeTab === 2" class="form-container">
      <input
          class="input-item"
          v-model="phone"
          type="number"
          placeholder="请输入手机号"
      />
      <view class="code-input">
        <input
            class="input-item"
            v-model="code"
            type="number"
            placeholder="请输入验证码"
        />
        <button
            class="send-code-btn"
            :disabled="countdown > 0"
            @click="sendSmsCode"
        >
          {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
        </button>
      </view>
    </view>

    <!-- QQ邮箱登录 -->
    <view v-show="activeTab === 3" class="form-container">
      <input
          class="input-item"
          v-model="email"
          type="text"
          placeholder="请输入QQ邮箱"
      />
      <view class="code-input">
        <input
            class="input-item"
            v-model="emailCode"
            :password="!showEmailCode"
            placeholder="请输入验证码"
        />
        <button
            class="send-code-btn"
            :disabled="countdown > 0"
            @click="sendQQEmailCode"
        >
          {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
        </button>
      </view>
    </view>

    <!-- 登录按钮 -->
    <button
        class="login-btn"
        @click="handleLogin"
    >
      {{ loginButtonText }}
    </button>

    <!-- 其他登录方式 -->
    <view class="other-login">
      <text>其他登录方式</text>
      <view class="icons">
        <image src="/static/wechat.png" class="icon"/>
        <image src="/static/qq.png" class="icon"/>
      </view>
    </view>
  </view>
</template>

<script setup>
import {computed, onUnmounted, ref} from 'vue'
import store from "../../store";
import LoginAPI from "../../api/LoginAPI";
import {formatDate} from "../../uni_modules/uni-dateformat/components/uni-dateformat/date-format";

const activeTab = ref(1) // 1:账号登录 2:手机登录 3:QQ邮箱
const account = ref('')
const password = ref('')
const phone = ref('')
const code = ref('')
const showPassword = ref(false)
const remember = ref(false)
const countdown = ref(0)
// 新增响应式数据
const email = ref('')
const emailCode = ref('')
const showEmailCode = ref(false)

// 修改登录按钮文本计算属性
const loginButtonText = computed(() => {
  return {
    1: '立即登录',
    2: '短信登录',
    3: '邮箱登录'
  }[activeTab.value]
})

// 发送短信验证码
const sendSmsCode = () => {
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    uni.showToast({title: '手机号格式错误', icon: 'none'})
    return
  }

  // 模拟发送手机验证码
  countdown.value = 60
  const timer = setInterval(() => {
    if (countdown.value <= 0) {
      clearInterval(timer)
      return
    }
    countdown.value--
  }, 1000)
}
// 发送QQ邮箱验证码
const sendQQEmailCode = () => {
  console.log(countdown)
  if (!validateEmail(email.value)) {
    uni.showToast({title: '请输入正确的QQ邮箱', icon: 'none'})
    return
  }
  console.log('发送QQ邮箱验证码', email.value)
  LoginAPI.QQMailSendCode.call({
    Email: email.value
  }).then(res => {
    if (res.code === 200) {
      // 弹窗提示用户验证码发送成功
      uni.showToast({
        title: '验证码发送成功，请查收',
        icon: 'none'
      })
      const timer = setInterval(() => {
        if (countdown.value <= 0) {
          clearInterval(timer)
          return
        }
        countdown.value--
      }, 3000000)
    }
  })
}
// 新增邮箱验证方法
const validateEmail = (email) => {
  return /^[a-zA-Z0-9_.-]+@qq\.com$/.test(email)
}

// 处理登录
const handleLogin = () => {
  if (activeTab.value === 1) {
    if (!account.value || !password.value) {
      uni.showToast({title: '请输入账号密码', icon: 'none'})
      return
    }

    const loginData = {
      username: account.value,
      password: password.value,
    }

    console.log('账号密码登录', account.value, password.value)
    // 调用账号登录接口
    LoginAPI.upLogin.call(
        JSON.stringify(loginData)
    ).then(res => {
      console.log(res)
      if (res.code === 200) {
        // 弹窗提示用户登录成功
        uni.showToast({
          title: '登录成功',
          icon: 'none'
        })
        console.log(res.data.access_token)
        // 先将token存入store中
        store.commit('token/SET_TOKEN', {
          token: res.data.access_token
        })
        // 检查一下有没有存进去
        console.log('token: ', store.getters["token/getToken"])
        getuserInfo().then(() => {
          uni.redirectTo({
            url: "/pages/index/index"
          })
        })
      }
    })


  } else if (activeTab.value === 2) {
    if (!phone.value || !code.value) {
      uni.showToast({title: '请输入手机号和验证码', icon: 'none'})
      return
    }
    // 调用手机登录接口
  } else if (activeTab.value === 3) {
    if (!validateEmail(email.value)) {
      uni.showToast({title: '请输入正确的QQ邮箱', icon: 'none'})
      return
    }
    if (!emailCode.value) {
      uni.showToast({title: '请输入密码', icon: 'none'})
      return
    }
    // 调用邮箱登录接口
    LoginAPI.QQMailLogin.call({
      Email: email.value,
      Code: emailCode.value
    }).then(res => {
      console.log('数据',res)
      if (res.code === 200) {
        console.log("code", res.data.code)
        // 弹窗提示用户登录成功
        uni.showToast({
          title: '登录成功',
          icon: 'none'
        })
        // 先将token存入store中
        store.commit('token/SET_TOKEN', {
          token: res.data.access_token
        })
        // 检查一下有没有存进去
        console.log(store.getters["token/getToken"])
        getuserInfo().then(() => {
          uni.redirectTo({
            url: "/pages/index/index"
          })
        })
      }else if (res.code != 200){
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  }
  // 登录逻辑...
  // uni.showLoading({ title: '登录中...' })

  // 再次发送请求，获取用户详细信息
  async function getuserInfo() {
    // 查询用户信息
    await LoginAPI.getUserInfo.call({
      userName: account.value,
      phoneNumber: phone.value,
      email: email.value
    }).then(res => {
      console.log(res)
      store.commit('token/SET_TOKEN', {
        token: store.getters['token/getToken'],
        username: res.data.userName,
        userID: res.data.userId,
      })
      const userInfo = {
        token: res.data.access_token,
        id: res.data.userId,
        name: res.data.userName,
        avatar: res.data.avatar,
        // roles: res.data.roles,
        // permissions: res.data.permissions
      }
      // store.commit('user/SET_USER', userInfo)
      // console.log(store.getters['user/getUserInfo'])
    })
  }
}
onUnmounted(() => {
  console.log(store.getters['token/getToken'])
  console.log(store.getters['token/getUserID'])
  console.log(store.getters['token/getIsLogin'])
  console.log(store.getters['token/getUsername'])
})
</script>

<style scoped>
.container {
  padding: 40rpx;
}

.tab-container {
  display: flex;
  margin-bottom: 60rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  padding: 20rpx 0;
  color: #666;
  border-bottom: 4rpx solid transparent;
}

.tab-item.active {
  color: #007AFF;
  border-bottom-color: #007AFF;
}

.form-container {
  margin-bottom: 60rpx;
}

.input-item {
  height: 100rpx;
  padding: 0 20rpx;
  margin-bottom: 30rpx;
  border: 2rpx solid #eee;
  border-radius: 12rpx;
}

.password-input, .code-input {
  position: relative;
}

.icon-eye {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
}

.code-input {
  display: flex;
  gap: 20rpx;
}

.send-code-btn {
  width: 240rpx;
  height: 100rpx;
  line-height: 100rpx;
  font-size: 28rpx;
  background-color: #f5f5f5;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28rpx;
  color: #666;
}

.forgot-password {
  color: #007AFF;
}

.login-btn {
  height: 100rpx;
  line-height: 100rpx;
  background-color: #007AFF;
  color: white;
  border-radius: 50rpx;
  font-size: 36rpx;
}

.other-login {
  margin-top: 100rpx;
  text-align: center;
  color: #999;
}

.icons {
  display: flex;
  justify-content: center;
  gap: 60rpx;
  margin-top: 40rpx;
}

.icon {
  width: 80rpx;
  height: 80rpx;
}
</style>